import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_mobx/flutter_mobx.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:katana_router/katana_router.dart';
import 'package:thal/backstage/blueprint/ai_chat_message_print.dart';
import 'package:thal/backstage/control_room/ai_chat_room.dart';
import 'package:thal/backstage/control_room/global_state_provider.dart';
import 'package:thal/backstage/toolkit/services/ai_chat_service.dart';
import 'package:thal/backstage/toolkit/utilities/asset_manifest.dart';
import 'package:thal/backstage/toolkit/utilities/color_palette.dart';
import 'package:thal/backstage/toolkit/utilities/dimension_rules.dart';
import 'package:thal/backstage/toolkit/widgets/report_focus_curtain.dart';
import 'package:thal/backstage/toolkit/widgets/stage_whisper.dart';

part 'ai_chat_production.page.dart';

/// AI聊天页面
@PagePath('/ai-chat')
class AiChatProduction extends StatefulWidget {
  const AiChatProduction({super.key});

  @pageRouteQuery
  static RouteQuery query() => const _$AiChatProductionQuery().call();

  @override
  State<AiChatProduction> createState() => _AiChatProductionState();
}

class _AiChatProductionState extends State<AiChatProduction> {
  final TextEditingController _messageController = TextEditingController();
  final ScrollController _scrollController = ScrollController();
  AiChatRoom? _aiChatRoom;

  // 默认问题
  final List<String> _defaultQuestions = [
    'The lake is an excellent spot for taking photos',
    'Which is the deepest lake',
    'Which are the most beautiful lakes',
  ];

  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    _messageController.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    _aiChatRoom ??= GlobalStateProvider.aiChatRoomOf(context);
    _aiChatRoom?.initSession();
  }

  /// 获取AI聊天状态管理
  AiChatRoom get aiChatRoom {
    _aiChatRoom ??= GlobalStateProvider.aiChatRoomOf(context);
    return _aiChatRoom!;
  }

  /// 发送消息
  Future<void> _sendMessage({String? content}) async {
    final message = content ?? _messageController.text.trim();
    if (message.isEmpty) return;

    // 清空输入框
    if (content == null) {
      _messageController.clear();
    }

    // 添加用户消息
    final userMessage = AiChatMessagePrint(
      id: DateTime.now().millisecondsSinceEpoch.toString(),
      content: message,
      isUser: true,
      createdAt: DateTime.now(),
    );
    aiChatRoom.addMessage(userMessage);

    // 滚动到底部
    _scrollToBottom();

    // 设置发送状态
    aiChatRoom.setSending(true);

    try {
      // 调用AI接口
      final response = await AiChatService.sendMessage(
        sessionId: aiChatRoom.sessionId,
        content: message,
        conversationId: aiChatRoom.conversationId,
      );

      if (response != null &&
          response['answer'] != null &&
          response['answer'].toString().isNotEmpty) {
        // 更新会话ID
        if (response['conversation_id'] != null) {
          aiChatRoom.setConversationId(response['conversation_id'].toString());
        }

        // 添加AI消息
        final aiMessage = AiChatMessagePrint(
          id: '${DateTime.now().millisecondsSinceEpoch}_ai',
          content: response['answer'].toString(),
          isUser: false,
          createdAt: DateTime.now(),
        );
        aiChatRoom.addMessage(aiMessage);

        // 滚动到底部
        _scrollToBottom();
      } else {
        StageWhisper.broadcast('AI is temporarily unavailable');
      }
    } catch (e) {
      StageWhisper.broadcast('Failed to send message');
    } finally {
      aiChatRoom.setSending(false);
    }
  }

  /// 滚动到底部
  void _scrollToBottom() {
    WidgetsBinding.instance.addPostFrameCallback((_) {
      if (_scrollController.hasClients) {
        _scrollController.animateTo(
          _scrollController.position.maxScrollExtent,
          duration: const Duration(milliseconds: 300),
          curve: Curves.easeOut,
        );
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Container(
        width: double.infinity,
        height: double.infinity,
        decoration: BoxDecoration(
          gradient: LinearGradient(
            begin: Alignment.topCenter,
            end: Alignment.bottomCenter,
            colors: [const Color(0xFFE0F2FE), const Color(0xFFDFF8F0)],
          ),
        ),
        child: SafeArea(
          bottom: false,
          child: Column(
            children: [
              // 固定顶部标题栏
              _buildHeader(),

              // 可滚动内容区域
              Expanded(
                child: SingleChildScrollView(
                  controller: _scrollController,
                  padding: EdgeInsets.symmetric(horizontal: 16.w),
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      // AI介绍
                      _buildAiIntroduction(),
                      40.h.heightBox,

                      // 默认问题
                      _buildDefaultQuestions(),
                      40.h.heightBox,

                      // 消息列表
                      Observer(
                        builder: (_) {
                          return Column(
                            children:
                                aiChatRoom.aiMessages
                                    .map(
                                      (message) => _buildMessageBubble(message),
                                    )
                                    .toList(),
                          );
                        },
                      ),
                      100.h.heightBox,
                    ],
                  ),
                ),
              ),

              // 固定底部输入框
              _buildInputField(),
            ],
          ),
        ),
      ),
    );
  }

  /// 构建顶部标题栏
  Widget _buildHeader() {
    return Container(
      padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 16.h),
      child: Row(
        children: [
          // 返回按钮
          GestureDetector(
            onTap: () => Navigator.of(context).pop(),
            child: Container(
              width: 40.w,
              height: 40.w,
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Icon(
                Icons.chevron_left_rounded,
                color: ColorPalette.black,
                size: 36.sp,
              ),
            ),
          ),
          12.w.widthBox,

          // 标题
          Expanded(
            child: Center(
              child: Text('Ai Chat')
                  .fontSize(24.sp)
                  .textColor(ColorPalette.black)
                  .carterOne(weight: FontWeight.w400),
            ),
          ),

          // 举报按钮
          GestureDetector(
            onTap: () {
              ReportAccusation.raise(
                context,
                targetId: 'ai_chat',
                onReportSubmitted: (reason) {
                  // 清空AI聊天消息
                  aiChatRoom.aiMessages.clear();
                  // 返回上一页面
                  Navigator.of(context).pop();
                  // 显示提示
                  StageWhisper.broadcast('Report submitted successfully');
                },
              );
            },
            child: Container(
              width: 40.w,
              height: 40.w,
              padding: EdgeInsets.all(8.w),
              decoration: BoxDecoration(
                color: ColorPalette.iconBg,
                shape: BoxShape.circle,
              ),
              child: Image.asset(
                AssetManifest.report2,
                width: 24.w,
                height: 24.w,
              ),
            ),
          ),
        ],
      ),
    );
  }

  /// 构建AI介绍
  Widget _buildAiIntroduction() {
    return Column(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Expanded(
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Container(
                    constraints: BoxConstraints(maxWidth: 180.w),
                    child: Text(
                          'Hello, \nI\'M KAELIX',
                          style: TextStyle(height: 1.2),
                        )
                        .fontSize(32.sp)
                        .textColor(ColorPalette.black)
                        .arimo(weight: FontWeight.w700),
                  ),
                  Container(
                    constraints: BoxConstraints(maxWidth: 180.w),
                    child: Text(
                          'FEEL FREE TO ASK ME ANY QUESTIONS YOU HAVE ~',
                          style: TextStyle(height: 1.5),
                        )
                        .fontSize(12.sp)
                        .textColor(const Color(0xFF666666))
                        .arimo(weight: FontWeight.w400),
                  ),
                ],
              ),
            ),
            // AI头像
            Container(
              width: 120.w,
              height: 120.w,
              decoration: BoxDecoration(
                image: DecorationImage(
                  image: AssetImage('assets/images/ai.png'),
                  fit: BoxFit.cover,
                ),
              ),
            ),
          ],
        ),
      ],
    );
  }

  /// 构建默认问题
  Widget _buildDefaultQuestions() {
    return Observer(
      builder: (_) {
        if (aiChatRoom.aiMessages.isNotEmpty) {
          return const SizedBox.shrink();
        }

        return Container(
          padding: EdgeInsets.all(16.w),
          decoration: BoxDecoration(
            color: const Color(0xFFF6FCFF),
            borderRadius: BorderRadius.circular(16.r),
            boxShadow: [
              BoxShadow(
                color: ColorPalette.black.withValues(alpha: 0.05),
                blurRadius: 10,
                offset: Offset(0, 5.h),
              ),
            ],
          ),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children:
                _defaultQuestions.map((question) {
                  return Padding(
                    padding: EdgeInsets.only(bottom: 12.h),
                    child: GestureDetector(
                      onTap: () => _sendMessage(content: question),
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 16.w,
                          vertical: 12.h,
                        ),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            begin: Alignment(0.00, 0.50),
                            end: Alignment(1.00, 0.50),
                            colors: [ColorPalette.blue2, ColorPalette.blue1],
                          ),
                          borderRadius: BorderRadius.circular(10.r),
                        ),
                        child: Row(
                          children: [
                            Text(
                              '•',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 20.sp,
                              ),
                            ),
                            8.w.widthBox,
                            Expanded(
                              child: Text(question)
                                  .fontSize(12.sp)
                                  .textColor(Colors.white)
                                  .arimo(weight: FontWeight.w700),
                            ),
                          ],
                        ),
                      ),
                    ),
                  );
                }).toList(),
          ),
        );
      },
    );
  }

  /// 构建消息气泡
  Widget _buildMessageBubble(AiChatMessagePrint message) {
    if (message.isUser) {
      // 用户消息 - 右侧
      return Padding(
        padding: EdgeInsets.only(
          bottom: 16.h,
          top: message == aiChatRoom.aiMessages.first ? 0 : 0,
        ),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.end,
          children: [
            Flexible(
              child: Container(
                constraints: BoxConstraints(maxWidth: 280.w),
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                decoration: BoxDecoration(
                  color: ColorPalette.blue3,
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: Text(message.content, style: TextStyle(height: 1.83))
                    .fontSize(14.sp)
                    .textColor(ColorPalette.blue1)
                    .arimo(weight: FontWeight.w400),
              ),
            ),
          ],
        ),
      );
    } else {
      // AI消息 - 左侧
      return Padding(
        padding: EdgeInsets.only(bottom: 16.h),
        child: Row(
          mainAxisAlignment: MainAxisAlignment.start,
          children: [
            Flexible(
              child: Container(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 12.h),
                constraints: BoxConstraints(maxWidth: 280.w),
                decoration: BoxDecoration(
                  color: Colors.white,
                  borderRadius: BorderRadius.circular(20.r),
                ),
                child: Text(message.content, style: TextStyle(height: 1.83))
                    .fontSize(14.sp)
                    .textColor(const Color(0xFF333333))
                    .arimo(weight: FontWeight.w400),
              ),
            ),
          ],
        ),
      );
    }
  }

  /// 构建输入框
  Widget _buildInputField() {
    return Observer(
      builder: (_) {
        return SizedBox(
          height: 105.h,
          child: Stack(
            children: [
              // 背景图片
              Positioned.fill(
                child: Image.asset(
                  AssetManifest.navigationBackground,
                  fit: BoxFit.fill,
                ),
              ),
              // 输入框内容
              Padding(
                padding: EdgeInsets.symmetric(horizontal: 16.w, vertical: 32.h),
                child: Row(
                  children: [
                    // 输入框
                    Expanded(
                      child: SizedBox(
                        height: 40.h,
                        child: TextField(
                          controller: _messageController,
                          enabled: !aiChatRoom.isSending,
                          textInputAction: TextInputAction.done,
                          decoration: InputDecoration(
                            hintText: 'Type here...',
                            hintStyle: TextStyle(
                              fontSize: 14.sp,
                              color: ColorPalette.black.withValues(alpha: 0.5),
                            ),
                            filled: true,
                            fillColor: Colors.transparent,
                            enabledBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(25.r),
                              borderSide: BorderSide(
                                color: const Color(0x99999999),
                                width: 1,
                              ),
                            ),
                            focusedBorder: OutlineInputBorder(
                              borderRadius: BorderRadius.circular(25.r),
                              borderSide: BorderSide(
                                color: const Color(0x99999999),
                                width: 1,
                              ),
                            ),
                            contentPadding: EdgeInsets.symmetric(
                              horizontal: 16.w,
                              vertical: 10.h,
                            ),
                            suffixIcon: Observer(
                              builder: (_) {
                                if (aiChatRoom.isSending) {
                                  return Padding(
                                    padding: EdgeInsets.all(12.w),
                                    child: SizedBox(
                                      width: 16.w,
                                      height: 16.w,
                                      child: CircularProgressIndicator(
                                        strokeWidth: 2,
                                        valueColor:
                                            AlwaysStoppedAnimation<Color>(
                                              const Color(0xFF3B82F6),
                                            ),
                                      ),
                                    ),
                                  );
                                }
                                return GestureDetector(
                                  onTap: () => _sendMessage(),
                                  child: Padding(
                                    padding: EdgeInsets.all(8.w),
                                    child: Image.asset(
                                      AssetManifest.send,
                                      width: 22.w,
                                      height: 22.w,
                                    ),
                                  ),
                                );
                              },
                            ),
                          ),
                          style: TextStyle(fontSize: 14.sp),
                          maxLines: null,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ),
        );
      },
    );
  }
}
